<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class City extends Base
{
//前置操作定义
    protected $beforeActionList = [
        // 'second' =>  ['except'=>'hello'],
        'beforeEdit'  =>  ['only'=>'edit,add'],
    ];
    private $mod;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('city');
    }
    public function index() {
        $sort  = input("param.sort", 'ordid');
        $order = input("param.order",'ASC');
        $tree = new \org\Tree();
        $tree->icon = ['│ ','├─ ','└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = $this->mod->order($sort . ' ' . $order)->select();
        $result = objToArray($result);
        $array = [];
        foreach($result as $r) {
            $r['str_status'] = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="status" data-value="'.$r['status'].'" src="/static/manage/images/toggle_' . ($r['status'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_hot']    = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="is_hot" data-value="'.$r['is_hot'].'" src="/static/manage/images/toggle_' . ($r['is_hot'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_manage'] = '<a href="javascript:;" class="J_showdialog" data-uri="'.url('City/add',['pid'=>$r['id']]).'" data-title="添加子栏目" data-id="add" data-width="500" data-height="360">添加子栏目</a> |
                                <a href="javascript:;" class="J_showdialog" data-uri="'.url('City/edit',['id'=>$r['id']]).'" data-title="编辑-'. $r['name'] .'" data-id="edit" data-width="500" data-height="360">编辑</a> |
                                <a href="javascript:;" class="J_confirmurl" data-acttype="ajax" data-uri="'.url('City/delete',['id'=>$r['id']]).'" data-msg="'.sprintf('确定要删除么？',$r['name']).'">删除</a>';
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';
            $r['str_default'] = $r['default'] == 1 ? '<span style="color:#ff0000;">是</span>' : '否';
            $array[] = $r;
        }
        $main_domain = config('url_domain_root');
        $str  = "<tr id='node-\$id' \$parentid_node>

                <td align='center'>\$id</td>
                <td>\$spacer<span data-tdtype='edit' data-field='name' data-id='\$id' class='tdedit'>\$name</span></td>
				<td align='center'>\$alias</td>
				<td align='center'>\$domain</td>
                <td align='center'><span data-tdtype='edit' data-field='ordid' data-id='\$id' class='tdedit'>\$ordid</span></td>

                <td align='center'>\$str_status</td>
                 <td align='center'>\$str_hot</td>
                 <td align='center'>\$str_default</td>
                <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($array);
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        //bigmenu (标题，地址，弹窗ID，宽，高)
        $big_menu = array(
            'title' => '添加城市',
            'iframe' => url('City/add'),
            'id' => 'add',
            'width' => '500',
            'height' => '360'
        );
        $this->assign('big_menu', $big_menu);
        $this->assign('list_table', true);
        return $this->fetch();
    }
    protected function beforeEdit(){
        $pid = input('param.pid/d');
        $spid = 0;
        if ($pid) {
            $spid = $this->mod->where(['id'=>$pid])->value('spid');
            $spid = $spid ? $spid.$pid : $pid;
        }
        $this->assign('spid', $spid);
    }
    public function addDo(){
        $data = input('post.');
        $name_arr = explode("\n",str_replace('&',"\n",trim($data['name'])));
        $aliasRadio = $data['aliasRadio'];
        unset($data['aliasRadio']);
        $py = new \org\Pinyin();
        $adddata = [];
        foreach($name_arr as $v){
            //检测分类是否存在
            if($this->mod->name_exists($data['name'], $data['pid'])){
                unset($v);
            }else{
                //生成spid
                $data['name'] = $v;
                $data['spid'] = $this->mod->get_spid($data['pid']);
                if(empty($data['alias'])){
                    $data['alias'] = $aliasRadio == 1 ? trim($py->getFirstPY($data['name'])) : trim($py->getAllPY($data['name']));
                }
                	//全部拼音
                $adddata[] = $data;
            }
        }
        if($this->mod->saveAll($adddata)){
            $this->ajaxReturn(1,'添加成功','','add');
        }else{
            $this->ajaxReturn(0,'添加失败','','add');
        }

    }
    public function delete(){
        //判断是否有下级栏目存在  存在则不能删除
        \app\manage\model\City::event('before_delete',function($obj){
            $id = $obj->id;
            //是否有下级栏目
            $child = $this->mod->get_child_ids($id);

            if(!empty($child)){
                return false;
            }
            return true;
        });
        parent::delete();
    }
    public function ajaxGetchilds() {
        $id = input('param.id/d');
        $return = $this->mod->field('id,name,spid')->where(['pid'=>$id,'status'=>1])->select();
        if ($return) {
            $this->ajaxReturn(1, 'success', $return);
        } else {
            $this->ajaxReturn(0, 'error');
        }
    }
    /**
     * 更新城市分类缓存
     */
    public function cache(){
        if($this->doCache()){
            $this->success('城市缓存更新成功');
        }else{
            $this->error('城市缓存更新失败');
        }
    }
    public function doCache(){
        $lists = $this->mod->field('id,pid,name,alias,is_hot,domain')->where('status',1)->select();
        if($lists){
            $cate = objToArray($lists);//普通列表
            $temp = [];
            foreach($cate as $v){
                $temp[$v['id']] = $v;
            }
            $tree = list_to_tree($temp);//树形列表
            cache('city',['cate'=>$temp,'tree'=>$tree]);
            return true;
        }
        return false;

    }
}